package com.ytjj.quartz.service;

import com.ytjj.qmyx.mall.model.ProductInfoStatistics;
import com.ytjj.quartz.dao.OrdersInfoDao;
import com.ytjj.quartz.dao.ProductInfoDao;
import com.ytjj.quartz.enums.ActivityTypeEnums;
import com.ytjj.quartz.enums.OrderSourceEnums;
import com.ytjj.quartz.model.ProductCategoryResp;
import com.ytjj.quartz.model.ProductInfoRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 *
 * @Version: 1.0
 */
@Service
@Slf4j
public class ProductInfoService {

    @Autowired
    private OrdersInfoDao ordersInfoDao;

    @Autowired
    private ProductInfoDao productInfoDao;

    public List<Integer> queryProductByStatus(Integer status) {
        List<Integer> bankerProductIds = productInfoDao.selectProductBankerProductId(status);
        return bankerProductIds;
    }

    public int updateProductStock(Integer bankerProductId, Integer stock) {
        return productInfoDao.updateProductStockByBankerProductId(bankerProductId, stock);
    }

//    @Transactional(rollbackFor = Exception.class)
    public void updateProductInfo(String startTime, String endTime) {

        // 获取活动类型activityType枚举集合
        ActivityTypeEnums[] array1 = ActivityTypeEnums.values();
        for (ActivityTypeEnums ate : array1) {
            // 获取平台类型orderSource枚举集合
            OrderSourceEnums[] array2 = OrderSourceEnums.values();
            for (OrderSourceEnums ce : array2) {
                ProductInfoRequest productInfo = new ProductInfoRequest();
                productInfo.setActivityType(ate.getCode());
                productInfo.setOrderSource(ce.getCode());
                productInfo.setStartTime(startTime);
                productInfo.setEndTime(endTime);
                // 普通商品信息
                if (ate.getCode().equals("ORDINARY_PRODUCT")) {
                    List<ProductInfoStatistics> infoList = ordersInfoDao.getProductInfo(productInfo);
                    if (!CollectionUtils.isEmpty(infoList)) {
                        for (ProductInfoStatistics ps : infoList) {
                            productInfo.setProductId(ps.getProductId());
                            ProductInfoStatistics statistics = new ProductInfoStatistics();
                            // 商品id
                            statistics.setProductId(ps.getProductId());
                            // 活动商品id
                            statistics.setActivityId(ps.getActivityId());
                            // 商品名称
                            statistics.setProductName(ps.getProductName());
                            // 活动类型
                            statistics.setActivityType(ps.getActivityType());
                            // 平台
                            statistics.setOrderSource(ce.getCode());
                            // uv
                            Integer uv = ordersInfoDao.getUvInfo(productInfo);
                            statistics.setUv(uv);
                            // 意向订单数
                            Integer orderNum = ordersInfoDao.getOrderNumInfo(productInfo);
                            statistics.setOrderNum(orderNum);
                            // 实际订单数
                            Integer realOrderNum = ordersInfoDao.getRealOrderNumInfo(productInfo);
                            statistics.setRealOrderNum(realOrderNum);
                            // 支付订单数
                            Integer payOrderNum = ordersInfoDao.getPayOrderNumInfo(productInfo);
                            statistics.setPayOrderNum(payOrderNum);
                            // 成本
                            BigDecimal costMoney = ordersInfoDao.getCostMoneyInfo(productInfo);
                            if (costMoney == null) {
                                costMoney = BigDecimal.ZERO;
                            }
                            statistics.setCostMoney(costMoney);
                            // 售价
                            BigDecimal price = ordersInfoDao.getPrice(productInfo);
                            if (price == null) {
                                price = BigDecimal.ZERO;
                            }
                            statistics.setPrice(price);
                            // 销售额
                            BigDecimal salesVolume = ordersInfoDao.getSalesVolume(productInfo);
                            if (salesVolume == null) {
                                salesVolume = BigDecimal.ZERO;
                            }
                            statistics.setSalesVolume(salesVolume);
                            // 利润 售价-成本
                            BigDecimal profix = BigDecimal.ZERO;
                            if (price != null && costMoney != null) {
                                profix = price.subtract(costMoney).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(payOrderNum.toString()));
                            }
                            statistics.setProfix(profix);
                            // 订单率 实际订单数/Uv
                            BigDecimal orderRatio = BigDecimal.ZERO;
                            if(uv != 0){
                                orderRatio = BigDecimal.valueOf(realOrderNum).divide(BigDecimal.valueOf(uv), 4, BigDecimal.ROUND_DOWN);
                            }
                            statistics.setOrderRatio(orderRatio);
                            // 支付率 支付订单数/实际订单数
                            BigDecimal payRatio = BigDecimal.ZERO;
                            if(realOrderNum != 0){
                                payRatio = BigDecimal.valueOf(payOrderNum).divide(BigDecimal.valueOf(realOrderNum), 4, BigDecimal.ROUND_DOWN);
                            }
                            statistics.setPayRatio(payRatio);

                            ProductInfoStatistics selProductInfo = productInfoDao.getStatistics(productInfo);

                            if (selProductInfo != null) {
                                statistics.setRecordTime(new Date());
                                productInfoDao.updateProductInfo(statistics);
                            } else {
                                statistics.setCreateTime(new Date());
                                statistics.setRecordTime(new Date());
                                productInfoDao.insertProductInfo(statistics);
                            }
                        }
                    }
                } else {
                    List<ProductInfoStatistics> infoList = ordersInfoDao.getActivityProductInfo(productInfo);
                    if (!CollectionUtils.isEmpty(infoList)) {
                        for (ProductInfoStatistics ps : infoList) {
                            productInfo.setProductId(ps.getProductId());
                            ProductInfoStatistics statistics = new ProductInfoStatistics();
                            // 商品id
                            statistics.setProductId(ps.getProductId());
                            // 活动商品id
                            statistics.setActivityId(ps.getActivityId());
                            // 商品名称
                            statistics.setProductName(ps.getProductName());
                            // 活动类型
                            statistics.setActivityType(ps.getActivityType());
                            // 平台
                            statistics.setOrderSource(ce.getCode());
                            // uv
                            Integer uv = ordersInfoDao.getActivityUv(productInfo);
                            statistics.setUv(uv);
                            // 意向订单数
                            Integer orderNum = ordersInfoDao.getActivityOrderNum(productInfo);
                            statistics.setOrderNum(orderNum);
                            // 实际订单数
                            Integer realOrderNum = ordersInfoDao.getActivityRealOrderNum(productInfo);
                            statistics.setRealOrderNum(realOrderNum);
                            // 支付订单数
                            Integer payOrderNum = ordersInfoDao.getActivityPayOrderNum(productInfo);
                            statistics.setPayOrderNum(payOrderNum);
                            // 成本
                            BigDecimal costMoney = ordersInfoDao.getActivityCostMoneyInfo(productInfo);
                            if (costMoney == null) {
                                costMoney = BigDecimal.ZERO;
                            }
                            statistics.setCostMoney(costMoney);
                            // 售价
                            BigDecimal price = ordersInfoDao.getActivityPrice(productInfo);
                            if (price == null) {
                                price = BigDecimal.ZERO;
                            }
                            statistics.setPrice(price);
                            // 销售额
                            BigDecimal salesVolume = ordersInfoDao.getActivitySalesVolume(productInfo);
                            if (salesVolume == null) {
                                salesVolume = BigDecimal.ZERO;
                            }
                            statistics.setSalesVolume(salesVolume);
                            // 利润 售价-成本
                            BigDecimal profix = BigDecimal.ZERO;
                            if (price != null && costMoney != null) {
                                profix = price.subtract(costMoney).setScale(2, BigDecimal.ROUND_DOWN);
                            }
                            statistics.setProfix(profix);

                            // 订单率 实际订单数/Uv
                            BigDecimal orderRatio = BigDecimal.ZERO;
                            if(uv != 0){
                                orderRatio = BigDecimal.valueOf(realOrderNum).divide(BigDecimal.valueOf(uv), 4, BigDecimal.ROUND_DOWN);
                            }
                            statistics.setOrderRatio(orderRatio);
                            // 支付率 支付订单数/实际订单数
                            BigDecimal payRatio = BigDecimal.ZERO;
                            if(realOrderNum != 0){
                                payRatio = BigDecimal.valueOf(payOrderNum).divide(BigDecimal.valueOf(realOrderNum), 4, BigDecimal.ROUND_DOWN);
                            }
                            statistics.setPayRatio(payRatio);

                            ProductInfoStatistics selProductInfo = productInfoDao.getStatistics(productInfo);

                            if (selProductInfo != null) {
                                statistics.setRecordTime(new Date());
                                productInfoDao.flushProductInfo(statistics);
                            } else {
                                statistics.setCreateTime(new Date());
                                statistics.setRecordTime(new Date());
                                productInfoDao.insertProductInfo(statistics);
                            }
                        }
                    }
                }
            }
        }

    }


    /**
     * //分类集合进行排序(三级放二级,二级放一级里)
     *
     * @param categoryList
     * @return
     */
    public List<ProductCategoryResp> getProductCategoryResps(List<ProductCategoryResp> categoryList) {
        List<ProductCategoryResp> categoryDTOList = new ArrayList<>();
        //查询所有父类目录
        for (ProductCategoryResp categoryEntity : categoryList) {
            if (categoryEntity.getPid() == 0) {
                categoryDTOList.add(categoryEntity);
            }
        }
        //查询子目录
        findSubCategory(categoryDTOList, categoryList);

        return categoryDTOList;
    }

    /**
     * 查询子目录
     * @param categoryDTOList 根目录
     * @param categoryEntityList
     */
    private void findSubCategory(List<ProductCategoryResp> categoryDTOList, List<ProductCategoryResp> categoryEntityList) {
        //遍历所有父类分类
        for (ProductCategoryResp categoryDTO : categoryDTOList) {
            List<ProductCategoryResp> subCategoryVoList = new ArrayList<>();
            //遍历父类下的cat_id与子类parent_cid相匹配的分类
            for (ProductCategoryResp category : categoryEntityList) {
                if (categoryDTO.getId().equals(category.getPid())) {
                    subCategoryVoList.add(category);
                }
                //设置subCategories
                categoryDTO.setChildProductCategory(subCategoryVoList);
            }
            //递归调用
            findSubCategory(subCategoryVoList, categoryEntityList);
        }
    }

    /**
     *  分类集合--例如-"[[1,2,3],[1,2,4],[5,6],[7]]"获取该集合里的集合中最后一个元素
     * @param productCategoryResp
     * @return
     */
    public List<Integer> getCategoryIds(List<ProductCategoryResp> productCategoryResp) {
        List<List<Integer>> categoryIdsList = new ArrayList<>();//分类集合--例如-"[[1,2,3],[1,2,4],[5,6],[7]]"
        productCategoryResp.forEach(category -> {
            List<ProductCategoryResp> childProductCategory = category.getChildProductCategory();
            if (!CollectionUtils.isEmpty(childProductCategory)) {
                childProductCategory.forEach(twoCategory -> {
                    List<ProductCategoryResp> bottomProductCategory = twoCategory.getChildProductCategory();
                    if (!CollectionUtils.isEmpty(bottomProductCategory)) {
                        bottomProductCategory.forEach(bottomCategory -> {
                            List<Integer> categoryIds = new ArrayList<>();
                            categoryIds.add(category.getId());
                            categoryIds.add(twoCategory.getId());
                            categoryIds.add(bottomCategory.getId());
                            categoryIdsList.add(categoryIds);
                        });
                    } else {
                        List<Integer> categoryIds = new ArrayList<>();
                        categoryIds.add(category.getId());
                        categoryIds.add(twoCategory.getId());
                        categoryIdsList.add(categoryIds);
                    }
                });
            } else {
                List<Integer> categoryIds = new ArrayList<>();
                categoryIds.add(category.getId());
                categoryIdsList.add(categoryIds);
            }
        });
        //获取categoryList里每个集合的最后一个索引作集合
        List<Integer> categoryIds = new ArrayList<>();
        categoryIdsList.forEach(categoryIdList -> {
            categoryIds.add(categoryIdList.get(categoryIdList.size() - 1));
        });
        return categoryIds;
    }

    public void updateProductReviews(){
        productInfoDao.updateProductReviews();
    }

}
